import pygame

from game_engine import WatermelonEnv


def human_play():
    """人类玩游戏的函数"""
    env = WatermelonEnv(render_mode="human")
    observation, info = env.reset()

    running = True
    while running:
        # 处理输入事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # 左键点击
                    # 获取鼠标位置
                    mouse_x, mouse_y = event.pos

                    # 只处理顶部区域的点击，防止点击已有水果
                    if mouse_y < 150:
                        # 直接设置位置并触发投放，不使用离散化动作
                        env.game.drop_position = mouse_x
                        env.game.drop_fruit()
                        # 更新游戏状态
                        observation, reward, terminated, truncated, info = env.step(
                            None
                        )

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    observation, info = env.reset()  # 重置游戏
                # 保留空格键投放功能作为替代方案
                elif event.key == pygame.K_SPACE:
                    observation, reward, terminated, truncated, info = env.step(2)

        # 每帧更新一次物理系统
        observation, reward, terminated, truncated, info = env.step(None)

        # 显示分数
        pygame.display.set_caption(f"合成大西瓜 | 得分: {info['score']}")

        # 判断游戏是否结束
        if terminated:
            if info["victory"]:
                print(f"恭喜你赢了! 成功合成西瓜! 最终得分: {info['score']}")
                # 显示胜利消息
                pygame.display.set_caption(f"胜利! 成功合成西瓜! 得分: {info['score']}")
            else:
                print(f"游戏结束! 最终得分: {info['score']}")
                pygame.display.set_caption(f"游戏结束! 得分: {info['score']}")

            pygame.time.wait(2000)  # 等待2秒
            observation, info = env.reset()

    env.close()


if __name__ == "__main__":
    human_play()
